package com.galacticconversion.service;

import com.galacticconversion.command.*;
import com.galacticconversion.model.DataStorage;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;

public class MerchantguideService {
    public static void main(String[] args) {
        // 初始化数据存储
        DataStorage dataStorage = new DataStorage();

        // 初始化命令映射关系，用于键为匹配输入格式的正则表达式模式，值为对应的命令处理器
        // 这种设计通过策略模式将输入格式与处理逻辑解耦，新增命令类型时只需添加新的键值对
        Map<Pattern, Command> commandMap = new HashMap<>();

        // 注册"单位定义"命令：匹配形如"glob is I"的输入
        // 用于建立星际单位（如glob）到罗马数字（如I）的映射关系
        commandMap.put(Pattern.compile("^\\w+ is [IVXLCDM]$"),
                new UnitDefinitionCommand(dataStorage));

        // 注册"金属价格定义"命令：匹配形如"glob glob Silver is 34 Credits"的输入
        // 用于计算并存储金属（如Silver）的单位价值
        commandMap.put(Pattern.compile("^(.+) (\\w+) is (\\d+) Credits$"),
                new MetalPriceCommand(dataStorage));

        // 注册"星际单位价值查询"命令：匹配形如"how much is pish tegj glob glob ?"的输入
        // 用于查询星际单位组合对应的十进制数值
        commandMap.put(Pattern.compile("^how much is (.+)\\?$"),
                new GalacticValueCommand(dataStorage));

        // 注册"金属价值查询"命令：匹配形如"how many Credits is glob prok Silver ?"的输入
        // 用于查询特定数量金属对应的总Credits价值
        commandMap.put(Pattern.compile("^how many Credits is ((?:\\w+ )+)\\w+ \\?$"),
                new MetalValueCommand(dataStorage));

        // 处理输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入命令（空行退出）：");

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (line.isEmpty()) break;

            boolean processed = false;
            for (Map.Entry<Pattern, Command> entry : commandMap.entrySet()) {
                if (entry.getKey().matcher(line).matches()) {
                    entry.getValue().execute(line);
                    processed = true;
                    break;
                }
            }

            if (!processed) {
                System.out.println("I have no idea what you are talking about");
            }
        }

        scanner.close();
    }
}
